package com.taptech.doufu.ui.view.choice;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Build;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.UmengEventName;
import com.taptech.doufu.bean.EventBean;
import com.taptech.doufu.bean.choice.BlockModel;
import com.taptech.doufu.bean.choice.NovelModel;
import com.taptech.doufu.weex.http.TFHttpError;
import com.taptech.doufu.weex.http.TFHttpResponse;
import com.taptech.doufu.weex.http.TFHttpUtil;
import com.taptech.doufu.ui.view.choice.adapter.ChoiceTopicOtherAdapter;
import com.taptech.doufu.ui.view.choice.listener.OnLayoutHeight;
import com.taptech.doufu.ui.view.topicview.MeasuredLinearLayoutManager;

import java.util.HashMap;
import java.util.List;

public class ChoiceTopicOtherContentView extends LinearLayout {
    private RecyclerView mRecyclerView;
    private BlockModel.Item model;
    private View layLoading;
    private View layReplace;
    private View layMore;
    private ImageView ivReplace;
    private boolean hasInit;
    private  List<NovelModel> list;
    private String replaceUrl;
    private EventBean eventData;
    private OnLayoutHeight onLayoutHeight;


    public ChoiceTopicOtherContentView(Context context) {
        super(context);
    }

    public ChoiceTopicOtherContentView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public ChoiceTopicOtherContentView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public ChoiceTopicOtherContentView(final Context context,
                                       List<NovelModel> list,
                                       BlockModel.Item item,
                                       final EventBean eventData,
                                       OnLayoutHeight onLayoutHeight) {
        this(context);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.topic_choice_other_content, null);
        this.onLayoutHeight = onLayoutHeight;
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        layLoading = view.findViewById(R.id.layLoading);
        layReplace = view.findViewById(R.id.layReplace);
        ivReplace = view.findViewById(R.id.ivReplace);
        layMore = view.findViewById(R.id.layMore);
        layLoading.setVisibility(View.GONE);
        model = item;
        this.eventData = eventData;
        this.list = list;
        replaceUrl = model.getReplaceUrl();
        if (list != null && list.size() > 0) {
            setData(list);
        }else{
            loadData();
        }
        if (TextUtils.isEmpty(item.getMoreUrl())) {
            layMore.setVisibility(View.GONE);
        }else{
            layMore.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(item.getReplaceUrl())) {
            layReplace.setVisibility(View.GONE);
        }else{
            layReplace.setVisibility(View.VISIBLE);
        }
        layMore.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ChoiceUtils.addEvent(context,UmengEventName.JINGXUAN_CARD_MORE,eventData);
                ChoiceUtils.jumpToMoreNovel(getContext(),model.getTitle(),model.getMoreUrl());
            }
        });
        layReplace.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                ChoiceUtils.addEvent(context,UmengEventName.JINGXUAN_CARD_REPLACE,eventData);
                startAnimator(ivReplace);
                getData(replaceUrl);
            }
        });
        addView(view);
    }

    public void loadData() {
        if (!hasInit) {
            hasInit = true;
            if (list.size() > 0) {
            }else{
                layLoading.setVisibility(View.VISIBLE);
                getData(model.getTabUrl());
            }
        }
    }

    private ObjectAnimator animator;
    protected void startAnimator(View view) {
        if (animator == null) {
            animator= ObjectAnimator.ofFloat(view, "rotation", 0f, 360f);
            animator.setInterpolator(new LinearInterpolator());
            animator.setRepeatCount(ObjectAnimator.INFINITE);
            animator.setRepeatMode(ObjectAnimator.RESTART);
            animator.setDuration(500);
        }
        animator.start();
    }

    protected void stopAnimator() {
        if (animator != null && animator.isRunning()) {
            animator.setRepeatCount(1);
        }
    }


    public void setData(List<NovelModel> list) {
        MeasuredLinearLayoutManager manager = new MeasuredLinearLayoutManager(getContext());
        ChoiceTopicOtherAdapter adapter = new ChoiceTopicOtherAdapter(getContext(), list,eventData);
        manager.setScrollEnabled(false);
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    mRecyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                if (mRecyclerView.getHeight() > 0) {
                    onLayoutHeight.onResult(mRecyclerView.getHeight());
                }
            }
        });
    }

    private void getData(String url) {
        if (TextUtils.isEmpty(url)) {
            layLoading.setVisibility(View.GONE);
            stopAnimator();
            return;
        }
        TFHttpUtil.requestGet(url, new HashMap(), new TFHttpResponse() {
            @Override
            public void onResponse(JSONObject json, TFHttpError error) {
                if (json != null && json.containsKey("data") &&
                        json.getJSONObject("data")!=null && json.getJSONObject("data").containsKey("list")) {
                    JSONObject jsonObject = json.getJSONObject("data");
                    String array = jsonObject.getString("list");
                    if (jsonObject.containsKey("moreUrl")) {
                        replaceUrl = jsonObject.getString("moreUrl");
                    }
                    List<NovelModel> list = JSON.parseArray(array, NovelModel.class);
                    if (list.size() > 0) {
                        setData(list);
                    }else{
                        Toast.makeText(getContext(),"无更多数据",Toast.LENGTH_LONG).show();
                    }
                }
                layLoading.setVisibility(View.GONE);
                stopAnimator();
            }
        });

    }
}
